﻿#region License
//------------------------------------------------------------
// Copyright (c) Denis Vuyka.  All rights reserved.
// This source code is subject to terms and conditions of the 
// Microsoft Reciprocal License (Ms-RL) License for Carcass. 
// A copy of the license can be found in the License.txt file 
// at the root of this distribution. 
// By using this source code in any fashion, you are agreeing 
// to be bound by the terms of the 
// Microsoft Reciprocal License (Ms-RL) License
// You must not remove this notice from this software.
//------------------------------------------------------------
#endregion

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows;
using Carcass.Events; 

namespace DemoShell
{
  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App : Application
  {
    private CompositionContainer _container;

    [Import(Carcass.GlobalContracts.MainWindow)]
    public new Window MainWindow
    {
      get { return base.MainWindow; }
      set { base.MainWindow = value; }
    }

    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      if (Compose())
      {
        MainWindow.Show();
      }
      else
      {
        Shutdown();
      }
    }

    protected override void OnExit(ExitEventArgs e)
    {
      base.OnExit(e);

      if (_container != null)
      {
        _container.Dispose();
      }
    }

    private bool Compose()
    {
      var catalog = new AggregateCatalog();
      catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
      catalog.Catalogs.Add(new AssemblyCatalog(typeof(Carcass.GlobalContracts).Assembly));
      catalog.Catalogs.Add(new DirectoryCatalog("AddIns", true));

      _container = new CompositionContainer(catalog);
      CompositionBatch batch = new CompositionBatch();
      batch.AddPart(this);
      //batch.AddExportedObject<ICompositionService>(_container);
      batch.AddExportedObject<ExportProvider>(_container);
      batch.AddExportedObject<IEventAggregator>(new EventAggregator());

      try
      {
        _container.Compose(batch);
      }
      catch (CompositionException compositionException)
      {
        MessageBox.Show(compositionException.ToString());
        return false;
      }
      return true;
    }
  }
}
